package com.blueocean_health.care.management.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.blueocean_health.care.management.common.base.em.TimeType;
import com.blueocean_health.care.management.common.base.string.StringUtils;
import com.blueocean_health.care.management.common.base.time.TimeUtils;
import com.blueocean_health.care.management.domain.base.OrderChargeInfo;
import com.blueocean_health.care.management.domain.base.OrderInfo;
import com.blueocean_health.care.management.domain.base.OrderRefundInfo;
import com.blueocean_health.care.management.domain.base.OrderServiceInfo;
import com.blueocean_health.care.management.domain.dto.OrderSelectInfoEntity;
import com.blueocean_health.care.management.domain.dto.RefundPayDetailsDto;
import com.blueocean_health.care.management.domain.dto.RefundPayDto;
import com.blueocean_health.care.management.domain.ordervo.ChareOrderVo;
import com.blueocean_health.care.management.domain.ordervo.RefundInfoVo;
import com.blueocean_health.care.management.em.FeeTypeEnum;
import com.blueocean_health.care.management.em.OrderStatusEnum;
import com.blueocean_health.care.management.em.PayStatusEnum;
import com.blueocean_health.care.management.em.RefundDealStatus;
import com.blueocean_health.care.management.exception.OrderException;
import com.blueocean_health.care.management.exception.OrderServiceException;
import com.blueocean_health.care.management.mapper.OrderChargeInfoMapper;
import com.blueocean_health.care.management.mapper.OrderInfoMapper;
import com.blueocean_health.care.management.mapper.OrderRefundInfoMapper;
import com.blueocean_health.care.management.mapper.OrderServiceInfoMapper;
import com.blueocean_health.care.management.service.IChareOrderService;
import com.blueocean_health.care.management.service.IOrderSelectService;
import com.blueocean_health.care.management.service.OrderInfoService;

import tk.mybatis.mapper.entity.Example;
@Service
public class ChareOrderServiceImpl implements IChareOrderService{
	@Resource
	private OrderChargeInfoMapper orderChargeInfoMapper;
	@Resource
	private OrderRefundInfoMapper orderRefundInfoMapper;
	@Resource
	private OrderServiceInfoMapper orderServiceInfoMapper;
	@Resource
	private IOrderSelectService iOrderSelectService;
	@Resource
	private OrderInfoService orderInfoService;
	@Resource
	private OrderInfoMapper orderInfoMapper;
	
	//新增收款信息 
	@Override
	public Integer receivables(ChareOrderVo chareo,FeeTypeEnum feeTypeEnum) {
		
		List<OrderChargeInfo> checkReceipt = orderChargeInfoMapper.checkReceipt(chareo);
		if(null!=checkReceipt&&checkReceipt.size()>0){
			return -1;
		}
		OrderChargeInfo orderChargeInfo=new OrderChargeInfo();
		BeanUtils.copyProperties(chareo, orderChargeInfo);
		Double chareoAmount = Double.valueOf(chareo.getAmount());
		orderChargeInfo.setAmount(chareoAmount);
		orderChargeInfo.setFeeType(feeTypeEnum.getKey());
		orderChargeInfo.setTime(new Date());
		orderChargeInfo.setHospitalId(chareo.getHospitalId());
		//orderChargeInfo.setBillingTime(TimeUtils.getDateByString(chareo.getBillingTime(),TimeType.yyyy_MM_dd));
		if("1".equals(feeTypeEnum.getKey())){
		String orderId = chareo.getOrderId();
		//应收金额
		Double receivableAmount = selectReceivableAmount(orderId);
		if(chareoAmount>=receivableAmount){
			//如果交款金额等于应收金额 则变成已付款
			iOrderSelectService.updateOrderInfoStatus(String.valueOf(chareo.getId()),PayStatusEnum._2);
		}}
		orderChargeInfo.setId(null);
		
		return  orderChargeInfoMapper.insertSelective(orderChargeInfo);
	}
	@Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public int receivableVo(ChareOrderVo chareo) throws Exception{
		if(chareo == null || StringUtils.isEmpty(chareo.getBillingTime())||StringUtils.isEmpty(chareo.getUserId())||StringUtils.isEmpty(chareo.getReceiptNumber())){
			throw new OrderServiceException("param error");
		}
		        Integer id = chareo.getId();
		    if(!StringUtils.isEmpty(id)&&id!=0){
		    	OrderInfo selectByPrimaryKey = orderInfoMapper.selectByPrimaryKey(id);
		    	if(selectByPrimaryKey.getPayStatus().equals(PayStatusEnum._2.getKey())){
		    		//状态已被改成收款 给提示
		    		return -2;
		    	}
		    }
	     	Boolean receivablesnew = receivablesnew(chareo);
		  if(receivablesnew){
		 	return 0;
		 }else{
			//收据编号重复
		 	return -1;
		}
	}
	//新增收款信息 
		@Override
	    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
		public Boolean receivablesnew(ChareOrderVo chareo) {
		
			//查询订单状态 根据订单状态判断收据状态
			List<OrderSelectInfoEntity> selectForList = iOrderSelectService.selectForList(chareo.getOrderId());
			if(null!=selectForList&&selectForList.size()>0){
				OrderSelectInfoEntity orderSelectInfoEntity = selectForList.get(0);
				chareo.setOrderType(orderSelectInfoEntity.getOrderType());
			}
			 //检查收据编号
			List<OrderChargeInfo> checkReceipt = orderChargeInfoMapper.checkReceipt(chareo);
			
			if(null!=checkReceipt&&checkReceipt.size()>0&&!chareo.getOrderType().equals("3")){
				return false;
			}
			//前端默认是true 添加  如果是false则是删除
			if(chareo.getIsReceivables()){	
			 Integer id = chareo.getId();
			 //如果有id 则根据id 更改状态
			    if(!StringUtils.isEmpty(id)&&id!=0){
			    	iOrderSelectService.updateOrderInfoStatus(String.valueOf(id),PayStatusEnum._2);
			    }
				Example example = new Example(OrderChargeInfo.class);
				String orderId = chareo.getOrderId();
				example.createCriteria().andEqualTo("orderId", orderId).andEqualTo("isActive", 1);
				//查询是否有此收据编号
				List<OrderChargeInfo> selectByExample = orderChargeInfoMapper.selectByExample(example);
				OrderChargeInfo orderChargeInfo=new OrderChargeInfo();
				BeanUtils.copyProperties(chareo, orderChargeInfo);
				orderChargeInfo.setFeeType(chareo.getOrderType());
				orderChargeInfo.setTime(new Date());
				orderChargeInfo.setHospitalId(chareo.getHospitalId());
				//orderChargeInfo.setBillingTime(TimeUtils.getDateByString(chareo.getBillingTime(),TimeType.yyyy_MM_dd));
				orderChargeInfo.setId(null);
				int insertSelective=0;
				//如果有则更新没有则新建
				if(null!=selectByExample&&selectByExample.size()>0){
				 insertSelective = orderChargeInfoMapper.updateByExampleSelective(orderChargeInfo, example);
				}else{
				 insertSelective = orderChargeInfoMapper.insertSelective(orderChargeInfo);
				}
				
				return  insertSelective>0;
			}else{
				orderChargeInfoMapper.updateChargeIsActive(chareo.getOrderId());
				return true;
			}
			
		}
	
	//获取续费信息
	@Override
	public Map<String, String> getRenew(ChareOrderVo chareo){
		List<OrderSelectInfoEntity> selectForList = iOrderSelectService.selectForList(chareo.getOrderId());
		OrderSelectInfoEntity orderSelectInfoEntity = selectForList.get(0);
		Map<String, String> map = new HashMap<String, String>();
		map.put("beginTime", orderSelectInfoEntity.getBeginTime());
		map.put("endTime", orderSelectInfoEntity.getEndTime());
		map.put("totalAmount",String.valueOf(orderSelectInfoEntity.getTotalAmount()));
		return map;
		
	}
	//查询应收金额
	@Override
	public Double selectReceivableAmount(String orderId){
		//已经交的钱
		Double alreadyAmount = orderChargeInfoMapper.AlreadyAmount(orderId);
		//订单的总价格
		Double selectOrdertotalAmount = iOrderSelectService.selectOrdertotalAmount(orderId);
		
		Double receivableAmount = (selectOrdertotalAmount==null?0:selectOrdertotalAmount)-(alreadyAmount==null?0:alreadyAmount);
		return receivableAmount;
		
	}
	//新增收款信息 退款類型
	@Override
	public Integer refundapply(RefundInfoVo refundInfoVo) {
		List<OrderSelectInfoEntity> selectForList = iOrderSelectService.selectForList(refundInfoVo.getOrderId());
		String orderStatus = selectForList.get(0).getOrderStatus();
		if(orderStatus.equals(OrderStatusEnum._4.getKey())||orderStatus.equals(OrderStatusEnum._5.getKey())){
			return -1;
		}
		OrderChargeInfo orderChargeInfo=new OrderChargeInfo();
		orderChargeInfo.setOrderId(refundInfoVo.getOrderId());
		orderChargeInfo.setAmount(Double.valueOf(refundInfoVo.getRefundActualAmount()));
		orderChargeInfo.setReceiptNumber(refundInfoVo.getRefundReceiptNumber());
		orderChargeInfo.setTransType(refundInfoVo.getRefundType());
		orderChargeInfo.setFeeType(FeeTypeEnum._3.getKey());
		orderChargeInfo.setTime(new Date());
		orderChargeInfo.setHospitalId(refundInfoVo.getHospitalId());
		orderChargeInfo.setBillingTime(TimeUtils.getDateByString(refundInfoVo.getPatientSignDate(),TimeType.yyyy_MM_dd));
		setRefundInfo(refundInfoVo);
		return  orderChargeInfoMapper.insertSelective(orderChargeInfo);
		
	}
	
	//新增退款表详情
	public void setRefundInfo(RefundInfoVo refundInfoVo) {
			OrderRefundInfo orderRefundInfo = new OrderRefundInfo();
		BeanUtils.copyProperties(refundInfoVo, orderRefundInfo);
		orderRefundInfo.setRefundAmount(Double.valueOf(refundInfoVo.getRefundAmount()));
		orderRefundInfo.setRefundActualAmount(Double.valueOf(refundInfoVo.getRefundActualAmount()));
		orderRefundInfo.setId(null);
		orderRefundInfo.setApplicationTime(new Date());
		orderRefundInfo.setRefundDealStatus(RefundDealStatus._0.getKey());
		orderRefundInfo.setPatientSignDate(TimeUtils.getDateByString(refundInfoVo.getPatientSignDate(), TimeType.yyyy_MM_dd));
		orderRefundInfo.setIsActive(1);
		orderRefundInfo.setRefundTime(TimeUtils.getDateByString(refundInfoVo.getRefundTime(),TimeType.yyyy_MM_dd_HH_mm_ss));
		orderRefundInfoMapper.insertSelective(orderRefundInfo);
		
	}
	@Override
	//查詢收据编号
	public List<String> selectreceipt(ChareOrderVo chareo) {
		List<OrderChargeInfo> receiptByOrderId = orderChargeInfoMapper.getReceiptByOrderId(chareo.getOrderId());
		List<String> selectreceipt=new ArrayList<String>();
		 for (OrderChargeInfo orderChargeInfo : receiptByOrderId) {
			 selectreceipt.add(orderChargeInfo.getReceiptNumber());
		}


		return selectreceipt;
	}
	@Override
	//查询退款信息
	public List<OrderRefundInfo> selectRefund(String orderId) {
		OrderRefundInfo orderRefundInfo = new OrderRefundInfo();
		orderRefundInfo.setOrderId(orderId);
		orderRefundInfo.setRefundDealStatus(RefundDealStatus._0.getKey());
		orderRefundInfo.setIsActive(1);
		List<OrderRefundInfo> selectByOrderId = orderRefundInfoMapper.select(orderRefundInfo);
		return selectByOrderId;
	}
	@Override
	//查询退款信息列表
	public List<OrderRefundInfo> selectRefundList(String orderId) {
		OrderRefundInfo orderRefundInfo = new OrderRefundInfo();
		orderRefundInfo.setOrderId(orderId);
		orderRefundInfo.setIsActive(1);
		List<OrderRefundInfo> selectByOrderId = orderRefundInfoMapper.select(orderRefundInfo);
		return selectByOrderId;
	}
	@Override
	//提交退款
	public Integer submitRefund(RefundInfoVo refundInfoVo) throws OrderException{
		List<OrderSelectInfoEntity> selectForList = iOrderSelectService.selectForList(refundInfoVo.getOrderId());
		String orderStatus = selectForList.get(0).getOrderStatus();
		if(!orderStatus.equals(OrderStatusEnum._4.getKey())){
			return -1;
		}
		OrderRefundInfo orderRefundInfo = new OrderRefundInfo();
		BeanUtils.copyProperties(refundInfoVo, orderRefundInfo);
		Example example = new Example(OrderRefundInfo.class);
		example.createCriteria().andEqualTo("orderId", refundInfoVo.getOrderId()).andEqualTo("refundDealStatus", RefundDealStatus._0.getKey()).andEqualTo("isActive",1);
		orderRefundInfo.setRefundDealTime(new Date());
		Integer updateByExampleSelective = orderRefundInfoMapper.updateByExampleSelective(orderRefundInfo, example);
		if(refundInfoVo.getRefundDealStatus().equals(RefundDealStatus._1.getKey())){
		orderInfoService.updateOrderInfoStatus(OrderStatusEnum._5.getKey(), Integer.parseInt(refundInfoVo.getId()));
		}
		if(refundInfoVo.getRefundDealStatus().equals(RefundDealStatus._2.getKey())){
			orderInfoService.updateOrderInfoStatus(OrderStatusEnum._3.getKey(), Integer.parseInt(refundInfoVo.getId()));
			}
		return updateByExampleSelective;
	}
	@Override
	//查询收款列表
	public List<OrderChargeInfo> selectChareList(String orderId){
		List<OrderChargeInfo> chargeListByOrderId = orderChargeInfoMapper.getChargeListByOrderId(orderId);
		return chargeListByOrderId;
	}
	@Override
	//查询已完成退款信息列表
		public List<OrderRefundInfo> selectRefundFinishList(String orderId) {
			OrderRefundInfo orderRefundInfo = new OrderRefundInfo();
			orderRefundInfo.setOrderId(orderId);
			orderRefundInfo.setRefundDealStatus(RefundDealStatus._1.getKey());
			orderRefundInfo.setIsActive(1);
			List<OrderRefundInfo> selectByOrderId = orderRefundInfoMapper.select(orderRefundInfo);
			return selectByOrderId;
		}
//	@Override
	//获取退款金额接口
	@Override
	public RefundPayDto selectRefundpay(RefundInfoVo refundInfoVo){
		RefundPayDto refundPayDto = new RefundPayDto();
		List<RefundPayDetailsDto> detail=new ArrayList<RefundPayDetailsDto>();
		String refundTime = refundInfoVo.getRefundTime();
		String orderId = refundInfoVo.getOrderId();
		List<OrderServiceInfo> orderServiceByOrderIdAndRefundTime = orderServiceInfoMapper.getOrderServiceByOrderIdAndRefundTime(orderId,refundTime);
		List<OrderServiceInfo> orderServiceByOrderIdAndStart = orderServiceInfoMapper.getOrderServiceByOrderIdAndStart(orderId, refundTime);
		List<OrderServiceInfo> orderServiceByOrderIdAndEnd = orderServiceInfoMapper.getOrderServiceByOrderIdAndEnd(orderId, refundTime);
		//未消费
		for (OrderServiceInfo orderServiceInfo : orderServiceByOrderIdAndEnd) {
			RefundPayDetailsDto refundPayDetailsDto=new RefundPayDetailsDto();
			BeanUtils.copyProperties(orderServiceInfo, refundPayDetailsDto);
			String dayhour = orderServiceInfo.getDay();
			String[] split = dayhour.split("\\.");
			String daystr = split[0];
			String hourstr="0";
			if(split.length>1){
				hourstr=split[1];
			}
			refundPayDetailsDto.setDay(Double.valueOf(daystr));
			refundPayDetailsDto.setHour(Double.valueOf(hourstr));
			refundPayDetailsDto.setFund(orderServiceInfo.getActualTotalPrice());
			refundPayDetailsDto.setIsUse(false);
			detail.add(refundPayDetailsDto);
		}
		//已消费
		for (OrderServiceInfo orderServiceInfo : orderServiceByOrderIdAndStart) {
			RefundPayDetailsDto refundPayDetailsDto=new RefundPayDetailsDto();
			BeanUtils.copyProperties(orderServiceInfo, refundPayDetailsDto);
			String dayhour = orderServiceInfo.getDay();
			String[] split = dayhour.split("\\.");
			String daystr = split[0];
			String hourstr="0";
			if(split.length>1){
				hourstr=split[1];
			}
			refundPayDetailsDto.setDay(Double.valueOf(daystr));
			refundPayDetailsDto.setHour(Double.valueOf(hourstr));
			refundPayDetailsDto.setFund(orderServiceInfo.getActualTotalPrice());
			refundPayDetailsDto.setIsUse(true);
			detail.add(refundPayDetailsDto);
		}
		if(orderServiceByOrderIdAndRefundTime!=null&&orderServiceByOrderIdAndRefundTime.size()==1){
			
			OrderServiceInfo orderServiceInfo = orderServiceByOrderIdAndRefundTime.get(0);
			String dayhour = orderServiceInfo.getDay();
			String[] split = dayhour.split("\\.");
			String daystr = split[0];
			String hourstr="0";
			if(split.length>1){
				hourstr=split[1];
			}
			Date beginTime = orderServiceInfo.getBeginTime();
			Date refundTimeD = TimeUtils.getDateByString(refundTime, TimeType.yyyy_MM_dd_HH_mm_ss);
			Date endTime = orderServiceInfo.getEndTime();
			//分钟数差
			int l=(int) ((refundTimeD.getTime()-beginTime.getTime())/1000/60);
			//按小时数差
			int i = 0;
			if(l%60==0){
				i=l/60;
			}else{
				i=l/60+1;
				refundTimeD=new Date(i*60*60*1000+beginTime.getTime());
			}
		
			//已消费天数
			int days = i/24;
			//小时价格
			Double halfDayPrice = orderServiceInfo.getOneHourPrice();
			//如果不能整除 按天分割
			if(i%24!=0){
				//已消费天数
				//判断当天的小时数,已消费当天小时数
				int hour=(int)(refundTimeD.getTime()-(beginTime.getTime()+(days*24*1000*60*60)))/1000/60/60;
				//当天已消费金额
				Double dayFinishPrice=halfDayPrice*hour;
				//如果大于日单价 钱不退了
				if(dayFinishPrice>=orderServiceInfo.getOneDayPrice()){
					RefundPayDetailsDto refundPayDetailsOld = new RefundPayDetailsDto();
					RefundPayDetailsDto refundPayDetailsNew = new RefundPayDetailsDto();
					BeanUtils.copyProperties(orderServiceInfo, refundPayDetailsOld);
					BeanUtils.copyProperties(orderServiceInfo, refundPayDetailsNew);
					refundPayDetailsOld.setIsUse(true);
					//refundPayDetailsOld.setActualDayPrice(orderServiceInfo.getActualDayPrice());
//					refundPayDetailsOld.setBeginTime(beginTime);
					refundPayDetailsOld.setEndTime(refundTimeD);
					refundPayDetailsOld.setDay(Double.valueOf(days));
					refundPayDetailsOld.setHour(Double.valueOf(hour));
					//refundPayDetailsOld.setServiceId(orderServiceInfo.getServiceId());
					refundPayDetailsOld.setFund((days+1)*orderServiceInfo.getOneDayPrice());
					refundPayDetailsNew.setIsUse(false);
					//refundPayDetailsNew.setActualDayPrice(orderServiceInfo.getActualDayPrice());
					refundPayDetailsNew.setBeginTime(refundTimeD);
					//refundPayDetailsNew.setEndTime(endTime);
					//总天数减去以服务天数再减一 
					Double weiDays=(Double.valueOf(daystr))-Double.valueOf(days)-1;
					if(Double.valueOf(hourstr)>=Double.valueOf(hour)){
						
						refundPayDetailsNew.setDay(weiDays+1);
						refundPayDetailsNew.setHour(Double.valueOf(hour)+Double.valueOf(hourstr)-24);
					}else{
						refundPayDetailsNew.setDay(weiDays);
						refundPayDetailsNew.setHour(Double.valueOf(hour)+Double.valueOf(hourstr));
					}
					//int xiaoshi=10;
//					refundPayDetailsOld.setServiceId(orderServiceInfo.getServiceId());
					refundPayDetailsNew.setFund(weiDays*orderServiceInfo.getOneDayPrice()+Double.valueOf(hourstr)*halfDayPrice);
					detail.add(refundPayDetailsOld);
					detail.add(refundPayDetailsNew);
				//如果小于日单价 钱得退了
				}else{
					RefundPayDetailsDto refundPayDetailsOld = new RefundPayDetailsDto();
					RefundPayDetailsDto refundPayDetailsNew = new RefundPayDetailsDto();
					refundPayDetailsOld.setIsUse(true);
					refundPayDetailsOld.setActualDayPrice(orderServiceInfo.getActualDayPrice());
					refundPayDetailsOld.setBeginTime(beginTime);
					refundPayDetailsOld.setEndTime(refundTimeD);
					refundPayDetailsOld.setDay(Double.valueOf(days));
					refundPayDetailsOld.setHour(Double.valueOf(hour));
					refundPayDetailsOld.setServiceId(orderServiceInfo.getServiceId());
					//天价格加上小时价格
					refundPayDetailsOld.setFund((days*orderServiceInfo.getOneDayPrice())+(hour*halfDayPrice));
					refundPayDetailsNew.setIsUse(false);
					refundPayDetailsNew.setActualDayPrice(orderServiceInfo.getActualDayPrice());
					refundPayDetailsNew.setBeginTime(refundTimeD);
					refundPayDetailsNew.setEndTime(endTime);
					//总天数减去以服务天数再减一 
					Double weiDays=(Double.valueOf(daystr))-Double.valueOf(days)-1;
					if(Double.valueOf(hourstr)>=Double.valueOf(hour)){
						refundPayDetailsNew.setDay(weiDays+1);
						refundPayDetailsNew.setHour((24-Double.valueOf(hour))+Double.valueOf(hourstr)-24);
					}else{
						refundPayDetailsNew.setDay(weiDays);
						refundPayDetailsNew.setHour((24-Double.valueOf(hour))+Double.valueOf(hourstr));
					}
					//int xiaoshi=10;
					refundPayDetailsNew.setServiceId(orderServiceInfo.getServiceId());
					refundPayDetailsNew.setFund(weiDays*orderServiceInfo.getOneDayPrice()+(orderServiceInfo.getOneDayPrice()-hour*halfDayPrice)+Double.valueOf(hourstr)*halfDayPrice);
					detail.add(refundPayDetailsOld);
					detail.add(refundPayDetailsNew);
				}
				//如果按天整除
			}else{
				RefundPayDetailsDto refundPayDetailsOld = new RefundPayDetailsDto();
				refundPayDetailsOld.setIsUse(true);
				refundPayDetailsOld.setActualDayPrice(orderServiceInfo.getActualDayPrice());
				refundPayDetailsOld.setBeginTime(beginTime);
				refundPayDetailsOld.setEndTime(refundTimeD);
				refundPayDetailsOld.setDay(Double.valueOf(days));
				refundPayDetailsOld.setHour((double) 0);
				refundPayDetailsOld.setServiceId(orderServiceInfo.getServiceId());
				refundPayDetailsOld.setFund(days*orderServiceInfo.getOneDayPrice());
				if(refundTimeD!=endTime){
				RefundPayDetailsDto refundPayDetailsNew = new RefundPayDetailsDto();
				refundPayDetailsNew.setIsUse(false);
				refundPayDetailsNew.setActualDayPrice(orderServiceInfo.getActualDayPrice());
				refundPayDetailsNew.setBeginTime(refundTimeD);
				refundPayDetailsNew.setEndTime(endTime);
				//总天数减去以服务天数
				Double weiDays=(Double.valueOf(daystr))-Double.valueOf(days);
				refundPayDetailsNew.setDay(weiDays);
				//int xiaoshi=10;
				refundPayDetailsNew.setHour(Double.valueOf(hourstr));
				refundPayDetailsNew.setServiceId(orderServiceInfo.getServiceId());
				refundPayDetailsNew.setFund(weiDays*orderServiceInfo.getOneDayPrice()+Double.valueOf(hourstr)*halfDayPrice);
				detail.add(refundPayDetailsNew);
				}
				detail.add(refundPayDetailsOld);
			}
			
		}else{
			refundPayDto.setRefundAmount("0");
			
		//	return refundPayDto;
		}
		refundPayDto.setDetails(detail);
		 refundPayDto = getAmountByPayDto(refundPayDto, orderId);
		 refundPayDto = getActualNursingTime(refundPayDto);
		return refundPayDto;
	}
	//计算护理时长
	public RefundPayDto getActualNursingTime(RefundPayDto refundPayDto){
		List<RefundPayDetailsDto> details = refundPayDto.getDetails();
		int day=0;
		int hour=0;
		for (RefundPayDetailsDto refundPayDetailsDto : details){
			if(refundPayDetailsDto.getIsUse()){
				day+=refundPayDetailsDto.getDay();
				hour+=refundPayDetailsDto.getHour();
			}
		}
		day=day+hour/24;
		hour=hour%24;
		if(day==0&&hour==0){
			refundPayDto.setActualNursingTime("0天");
		}else
		refundPayDto.setActualNursingTime((day==0?"":day+"天")+(hour==0?"":hour+"小时"));
		return refundPayDto;
		
	}
	//计算总应退费用
	public RefundPayDto getAmountByPayDto(RefundPayDto refundPayDto,String orderId){
		List<RefundPayDetailsDto> details = refundPayDto.getDetails();
		//订单已经消费的钱数
		Double sumfund=0.0;
		for (RefundPayDetailsDto refundPayDetailsDto : details) {
			if(refundPayDetailsDto.getIsUse()) {
				Double fund = refundPayDetailsDto.getFund();
				sumfund+=fund;
			}
		}
		Double alreadyAmount = orderChargeInfoMapper.AlreadyAmount(orderId);
		Double double1 = (alreadyAmount==null?0:alreadyAmount)-(sumfund==null?0:sumfund);
		BigDecimal   b   =   new   BigDecimal(double1);  
		   double1   =   b.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue(); 
		refundPayDto.setRefundAmount(String.valueOf(double1));
		return refundPayDto;
		
		
	}
	@Override
	 @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void emptyChare(ChareOrderVo chareo) {
		orderChargeInfoMapper.updateChargeIsActive(chareo.getOrderId());
		OrderRefundInfo orderRefundInfo = new OrderRefundInfo();
		orderRefundInfo.setIsActive(0);
		Example example = new Example(OrderRefundInfo.class);
		example.createCriteria().andEqualTo("orderId", chareo.getOrderId());
		orderRefundInfoMapper.updateByExampleSelective(orderRefundInfo, example);
		List<OrderSelectInfoEntity> selectForList = iOrderSelectService.selectForList(chareo.getOrderId());
		String beginTime = selectForList.get(0).getBeginTime();
		if(!StringUtils.isEmpty(beginTime)){
		long dateByString = TimeUtils.getDateByString(beginTime, TimeType.yyyy_MM_dd_HH_mm_ss).getTime();
		try {
			//如果开始时间大于当前时间 则变成未服务否则变成服务中
		if(dateByString>new Date().getTime()){
				orderInfoService.updateOrderInfoStatus(OrderStatusEnum._2.getKey(), chareo.getId());
		}else{
			orderInfoService.updateOrderInfoStatus(OrderStatusEnum._3.getKey(), chareo.getId());
		}
		} catch (OrderException e) {
			e.printStackTrace();
		}
		}
		//变成未付款
		iOrderSelectService.updateOrderInfoStatus(String.valueOf(chareo.getId()),PayStatusEnum._1);
	}
	@Override
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public Boolean delCharge(String[] orderId) {
		StringBuilder sb = new StringBuilder(orderId.length*3);
		for( int i = 0, len = orderId.length; i < len; i++)
		{
		   if( i > 0 ){
		      sb.append(", ");
		   }
		   sb.append(orderId[i]);
		}
		String orderIdStr = sb.toString();
		return orderChargeInfoMapper.updateAllChargeActive(orderIdStr);
		
	}
	public static void main(String[] args) throws Exception {
//		int l=(int) (59999/1000);
//		int i = l%60==0?l/60:(l/60)+1;
//		System.out.println(i);
//		int[][] i1={{10,90},{20,90},{30,90}};
//		int[][] i2={{10,80},{20,80},{30,80}};
//		int[][] i3={{10,70},{20,70},{30,70}};
//		int[][] i4={{10,60},{20,60},{30,60}};
//		int[][][] i5={i1,i2,i3,i4};
//		String i5str = Arrays.deepToString(i5);
//		System.out.println(i5str);
//		double sqrt = Math.sqrt(9);
//		System.out.println(sqrt);
//		String format = String.format("%.2f", 2.9944);
//		System.out.println(format);
//		  File file = new File("E:/aaa.txt");
//		  String txt2String = txt2String(file);
//	        System.out.println(txt2String);
//		JSONArray parseArray = JSONObject.parseArray(txt2String);
//		   for(int i=0 ; i < parseArray.size() ;i++){
//			   JSONObject jsonObject = parseArray.getJSONObject(i);
//			   String id = String.valueOf(jsonObject.get("id"));
//			   String name = String.valueOf(jsonObject.get("name"));
//				System.out.println("id:  "+id+"\t name:  "+name);
//		   }
		
		
//		   JSONObject json_test = JSONObject.parseObject(txt2String);
//		String object = String.valueOf(json_test.get("id"));
//		System.out.println(object);
	}
	public static String txt2String(File file){
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法，一次读一行
                result.append(System.lineSeparator()+s);
            }
            br.close();    
        }catch(Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }
    
}
